package com.leyou.auth.config;

import com.leyou.common.auth.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.security.PrivateKey;
import java.security.PublicKey;

@Data
@Slf4j
@ConfigurationProperties(prefix = "ly.jwt")
public class JwtProperties implements InitializingBean {

    //公钥地址
    private String pubKeyPath;
    //私钥地址
    private String priKeyPath;

    private PublicKey publicKey;

    private PrivateKey privateKey;

    private UserTokenProperties user = new UserTokenProperties();

    private AppTokenProperties app = new  AppTokenProperties();

    @Data
    public class AppTokenProperties{
        //token过期时长
        private int expire;

        //服务id，这里为 10
        private Long id;

        //秘钥 这里为 auth-service
        private String secret;

        //token在请求头中的名称
        private String headerName;
    }

    @Data
    public class UserTokenProperties{
        //token过期时长
        private int expire;

        //cookie的名称
        private String cookieName;

        //cookie的域，可让该域名下的所有二级域获取此cookie
        private String cookieDomain;

        //最少刷新时间间隔 15分钟
        private int minRefreshInterval;

        //刷新token的周期
        private int refreshInterval;
    }



    /**
     * 保存公钥与私钥，在spring完成属性注入之后再读取公钥与私钥
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和私钥失败！", e);
            throw new RuntimeException(e);
        }
    }
}